package redis

import (
	"context"
	"errors"
	"github.com/redis/go-redis/v9"
	"sync"
	"time"
)

//// 集群模式
//func NewClusterRedisClient(opt *redis.ClusterOptions) *redis.ClusterClient {
//	return redis.NewClusterClient(opt)
//}
//
//// 哨兵模式
//func NewFailoverRedisClient(opt *redis.FailoverOptions) *redis.Client {
//	return redis.NewFailoverClient(opt)
//}

type RedisClient struct {
	//model   string //模式
	rdb *redis.Client
	opt *redis.Options
}

var global = &RedisClient{}

func NewRedisClient(opt *redis.Options) *RedisClient {
	rdb := redis.NewClient(opt)
	return &RedisClient{
		rdb: rdb,
		opt: opt,
	}
}

func SetGlobalRedis(c *RedisClient) {
	var lock sync.Mutex
	lock.Lock()
	defer lock.Unlock()
	global = c
}

func GetGlobalRedis() *RedisClient {
	return global
}

func Set(ctx context.Context, key string, value string, expiration time.Duration) error {
	if global.rdb == nil {
		return errors.New("Global rdb initialization failed")
	}
	err := global.rdb.Set(ctx, key, value, expiration).Err()
	return err
}

func Get(ctx context.Context, key string) (string, error) {
	if global.rdb == nil {
		return "", errors.New("Global rdb initialization failed")
	}
	val, err := global.rdb.Get(ctx, key).Result()
	if err == redis.Nil {
		return "", errors.New("key不存在")
	} else if err != nil {
		return "", err
	} else if val == "" {
		return "", errors.New("值是空字符串")
	} else {
		//获取成功
		return val, nil
	}

}
